<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Config;
use app\common\model\FamilyTree;
use app\common\model\Room;
use app\common\model\RoomLevel;
use app\common\model\RoomUser;
use app\common\model\User;
use think\Db;
use think\Exception;

class Home extends Api{
    //protected $noNeedLogin = ['con'];
    protected $noNeedRight = '*';

    /**
     * 获取族谱地图数据
     */
    public function getGenealogyMap(){
        $roomId = User::where('id',$this->auth->id)->value('g_room_id');
        $roomInfo = Room::where('id',$roomId)->where('types',1)->find();
        if(empty($roomInfo)){
            $this->error('系统内部参数错误，请联系管理员');
        }
        $roomInfo = $roomInfo->toArray();
        $startYesterday = date("Y-m-d",strtotime("-1 day"));
        $endYesterday = date("Y-m-d 23:59:59",strtotime("-1 day"));
        $roomInfo['yesterday_add_male'] = User::where('g_room_id',$roomId)->where('gender',1)->where('createtime','>=',strtotime($startYesterday))->where('createtime','<=',strtotime($endYesterday))->count();
        $roomInfo['yesterday_add_woman'] = User::where('g_room_id',$roomId)->where('gender',0)->where('createtime','>=',strtotime($startYesterday))->where('createtime','<=',strtotime($endYesterday))->count();
        $roomInfo['yesterday_del_male'] = User::where('g_room_id',$roomId)->where('gender',1)->where('die_time','>=',$startYesterday)->where('die_time','<=',$endYesterday)->count();
        $roomInfo['yesterday_del_woman'] = User::where('g_room_id',$roomId)->where('gender',0)->where('die_time','>=',$startYesterday)->where('die_time','<=',$endYesterday)->count();

        // 按姓氏查询家庭虚拟人数
        if($this->auth->surname){
            $roomInfo['yesterday_add_male'] += FamilyTree::where('user_id',0)->where('gender',1)->where('name','like',$this->auth->surname.'%')->where('created_at','>=',$startYesterday)->where('created_at','<=',$endYesterday)->count();
            $roomInfo['yesterday_add_woman'] += FamilyTree::where('user_id',0)->where('gender',0)->where('name','like',$this->auth->surname.'%')->where('created_at','>=',$startYesterday)->where('created_at','<=',$endYesterday)->count();
            $roomInfo['yesterday_del_male'] += FamilyTree::where('user_id',0)->where('gender',1)->where('name','like',$this->auth->surname.'%')->where('end_time','>=',$startYesterday)->where('end_time','<=',$endYesterday)->count();
            $roomInfo['yesterday_del_woman'] += FamilyTree::where('user_id',0)->where('gender',0)->where('name','like',$this->auth->surname.'%')->where('end_time','>=',$startYesterday)->where('end_time','<=',$endYesterday)->count();
            $roomInfo['alive_male_count'] += FamilyTree::where('user_id',0)->where('gender',1)->where('name','like',$this->auth->surname.'%')->where('end_time IS NULL')->count();
            $roomInfo['alive_woman_count'] += FamilyTree::where('user_id',0)->where('gender',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NULL')->count();
            $roomInfo['die_male_count'] += FamilyTree::where('user_id',0)->where('gender',1)->where('name','like',$this->auth->surname.'%')->where('end_time IS NOT NULL')->count();
            $roomInfo['die_woman_count'] += FamilyTree::where('user_id',0)->where('gender',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NOT NULL')->count();

        }

        // 在世人员分布
        $map = User::where('g_room_id',$roomId)->where('die_time IS NULL')->group('province')->field('province,count(*) as count')->select();
        $proIds = [];
        $pro1 = [];
        foreach($map as $v){
            if(!empty($v['province'])){
                $proIds[] = $v['province'];
                $arr = Area::where('level',1)->where('name',$v['province'])->field('shortname as name')->find();
                //$arr->value = $v['count'];
                if(!empty($arr)){
                    $arr = $arr->toArray();
                    $arr['value'] = $v['count'];
                    if($this->auth->surname){
                        $arr['value'] += FamilyTree::where('user_id',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NULL')->where('province',$v['province'])->count();
                    }
                    $pro1[] = $arr;
                }
            }
        }
        if($this->auth->surname){
            $surnameMap = FamilyTree::where('user_id',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NULL')->group('province')->field('end_time,province,count(*) as count')->select();
            foreach($surnameMap as $v){
                if(!in_array($v['province'],$proIds) && !empty($v['province'])){
                    $proIds[] = $v['province'];
                    $arr = Area::where('level',1)->where('name',$v['province'])->field('shortname as name')->find();
                    //$arr->value = $v['count'];
                    if(!empty($arr)){
                        $arr = $arr->toArray();
                        $arr['value'] = $v['count'];
                        $pro1[] = $arr;
                    }
                }
            }
        }
        $pro = Area::where('level',1)->where('name','not in',$proIds)->field('shortname as name')->select()->toArray();
        $roomInfo['map'] = array_merge($pro,$pro1);

        // 去世人员分布
        $map = User::where('g_room_id',$roomId)->where('die_time IS NOT NULL')->group('province')->field('province,count(*) as count')->select();
        $proIds = [];
        $pro1 = [];
        foreach($map as $v){
            if(!empty($v['province'])){
                $proIds[] = $v['province'];
                $arr = Area::where('level',1)->where('name',$v['province'])->field('shortname as name')->find();
                //$arr->value = $v['count'];
                if(!empty($arr)){
                    $arr = $arr->toArray();
                    $arr['value'] = $v['count'];
                    if($this->auth->surname){
                        $arr['value'] += FamilyTree::where('user_id',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NOT NULL')->where('province',$v['province'])->count();
                    }
                    $pro1[] = $arr;
                }
            }
        }
        if($this->auth->surname){
            $surnameMap = FamilyTree::where('user_id',0)->where('name','like',$this->auth->surname.'%')->where('end_time IS NOT NULL')->group('province')->field('end_time,province,count(*) as count')->select();
            foreach($surnameMap as $v){
                if(!in_array($v['province'],$proIds) && !empty($v['province'])){
                    $proIds[] = $v['province'];
                    $arr = Area::where('level',1)->where('name',$v['province'])->field('shortname as name')->find();
                    //$arr->value = $v['count'];
                    if(!empty($arr)){
                        $arr = $arr->toArray();
                        $arr['value'] = $v['count'];
                        $pro1[] = $arr;
                    }
                }
            }
        }
        $pro = Area::where('level',1)->where('name','not in',$proIds)->field('shortname as name')->select()->toArray();
        $roomInfo['die_map'] = array_merge($pro,$pro1);
        // 完成任务
        \app\common\model\Task::complete(2,$this->auth->id);
        $roomInfo['user_count'] = $roomInfo['alive_male_count']+$roomInfo['alive_woman_count']+$roomInfo['die_male_count']+$roomInfo['die_woman_count'];
        $this->success('请求成功',$roomInfo);
    }

    /**
     * 家族树信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function treeInfo(){
        $roomId = RoomUser::where('user_id',$this->auth->id)->where('types',2)->value('room_id');
        if(empty($roomId)){
            $this->error('家族不存在');
        }
        $roomInfo = Room::with('levelInfo')->where('id',$roomId)->field('id,level,score')->find();
        if(empty($roomInfo)){
            $this->error('家族不存在');
        }
        $this->success('请求成功',$roomInfo);
    }

    /**
     * 家族成员列表
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function familyTreeUserList(){
        $roomId = request()->post('room_id');
        $page = request()->post('page',1);
        $limit = request()->post('limit',config('paginate.list_rows'));
        $count = RoomUser::where('room_id',$roomId)->where('user_id',$this->auth->id)->where('types',2)->count();
        if($count < 1){
            $this->error('家族不存在');
        }
        $list = RoomUser::with('user')->where('room_id',$roomId)->order('score','desc')->page($page,$limit)->select();
        $this->success('请求成功',$list);
    }

    /**
     * 浇水/施肥
     * @throws Exception
     */
    public function con(){
        $type = request()->post('type',1); // 1=浇水,2=施肥
        $roomId = RoomUser::where('user_id',$this->auth->id)->where('types',2)->value('room_id');
        if(empty($roomId)){
            $this->error('家族不存在');
        }
        $count = Room::where('id',$roomId)->count();
        if($count < 1){
            $this->error('家族不存在');
        }
        if($type == 1){
            // 浇水
            $xh_gxz = Config::getValue('js_xh_gxz','family_tree');
            $hd_gxs = Config::getValue('js_hd_gxs','family_tree');
            $jz_hd_gxs = Config::getValue('js_jz_hd_gxs','family_tree');
            $changeType = 4010;
            $changeType2 = 4020;
            $msg = '浇水';
        }else{
            // 施肥
            $xh_gxz = Config::getValue('sf_xh_gxz','family_tree');
            $hd_gxs = Config::getValue('sf_hd_gxs','family_tree');
            $jz_hd_gxs = Config::getValue('sf_jz_hd_gxs','family_tree');
            $changeType = 4030;
            $changeType2 = 4040;
            $msg = '施肥';
        }
        if($this->auth->money < $xh_gxz){
            $this->error('贡献值不足','','10');
        }
        Db::startTrans();
        try{
            $time = time();
            $s1 = User::setMoney($this->auth->id,'money',-$xh_gxz,$changeType,'家族'.$msg.'消耗',$this->auth->id . $time);
            if(!$s1){
                throw new Exception('贡献值扣除失败');
            }
            $s2 = User::setMoney($this->auth->id,'score',$hd_gxs,$changeType2,'家族'.$msg.'获得',$this->auth->id . $time);
            if(!$s2){
                throw new Exception('增加贡献史失败');
            }else{
                RoomUser::where('user_id',$this->auth->id)->where('room_id',$roomId)->setInc('score',$hd_gxs);
                Room::where('id',$roomId)->setInc('score',$jz_hd_gxs);
            }
            // 家族升级
            $roomInfo = Room::where('id',$roomId)->find();
            $roomLevel = RoomLevel::where('money','<=',$roomInfo['score'])->order('money','desc')->find();
            if(!empty($roomLevel) && $roomLevel['id'] != $roomInfo['level']){
                Room::where('id',$roomId)->update([
                    'level' => $roomLevel['id']
                ]);
            }
            if($type == 1){
                \app\common\model\Task::complete(6,$this->auth->id);
            }
            Db::commit();
            $this->success('操作成功',$jz_hd_gxs);
        }catch(Exception $e){
            Db::rollback();
            write_log($e->getMessage(),'浇水施肥错误');
            $this->error('系统错误!');
        }
    }
}